'use strict';
// +----------------------------------------------------------------------
// | CmPage [ 通用页面框架 ] 手机APP数据接口
// +----------------------------------------------------------------------
// | Licensed under the Apache License, Version 2.0
// +----------------------------------------------------------------------
// | Author: defans <defans@sina.cn>
// +----------------------------------------------------------------------

/**
 @module cmpage.controller
 */

/**
 * 移动端，业务模块展示及常用操作的URL接口
 * @class cmpage.controller.mob
 */
const Base = require('./base.js');

module.exports = class extends Base {
    /**
     * 业务模块展示的主界面，分页列表，POST调用： /cmpage/mob/list
     * @method  list
     * @return {json}  包含HTML片段
     */
    async listAction() {
        let vb = {};
        let moduleApp = cmpage.service("cmpage/module");

        let parms = {};
        parms.modulename = this.post('modulename');
        if (parms.modulename.length > 20) {
            return this.json({
                statusCode: '300',
                message: parms.modulename + " 模块名错误！"
            });
        }
        parms.pageIndex = this.post('pageIndex');
        parms.pageSize = this.post('pageSize');
        parms.parmsUrl = JSON.parse(this.post('parmsUrl')) || {};
        Object.assign(vb, parms);
        //debug(parms,'cmpage.ctrl.mob - parms');

        let md = await moduleApp.getModuleByName(parms.modulename);
        Object.assign(parms, md);

        parms.query = this.post();
        parms.c_page_size = parms.pageSize;
        //console.log(page);
        parms.user = await this.session('user');
        //    console.log(page);
        if (think.isEmpty(parms.id)) {
            return this.json({
                statusCode: '300',
                message: parms.modulename + " 模块不存在！"
            });
        }

        let pageModel = cmpage.service(parms.c_path);
        if (think.isEmpty(pageModel)) {
            return this.json({
                statusCode: '300',
                message: parms.modulename + " 的实现类不存在！"
            });
        }
        debug(parms.query, 'cmpage.C.mob - parms.query');
        pageModel.mod = parms;
        pageModel.modQuerys = await moduleApp.getModuleQuery(parms.id);
        pageModel.modCols = await moduleApp.getModuleCol(parms.id);
        pageModel.modBtns = await moduleApp.getModuleBtn(parms.id);

        //拆分联动的下拉选择
        for (const modQ of pageModel.modQuerys) {
            if (pageModel.mod.query[modQ.c_column] && (modQ.c_type === 'areaSelect' || modQ.c_type === 'codeSelect') && !think.isEmpty(modQ.c_memo)) {
                //cmpage.warn(modQ,'cmpage.C.mob.list - modQ');
                let values = parms.query[modQ.c_column].split(',');
                if (values.length === 2) {
                    pageModel.mod.query[modQ.c_memo] = values[0];
                    pageModel.mod.query[modQ.c_column] = values[1];
                } else if (values.length === 3) {
                    let keys = modQ.c_memo.split(',');
                    pageModel.mod.query[keys[0]] = values[0];
                    pageModel.mod.query[keys[1]] = values[1];
                    pageModel.mod.query[modQ.c_column] = values[2];
                }
            }
        }
        //cmpage.warn(pageModel.mod.query,'cmpage.C.mob.list - parms');

        vb.queryHtml = await pageModel.mobHtmlGetQuery();
        let btnsHtml = await pageModel.mobHtmlGetHeaderBtns();
        vb.headerBtnsHtml = btnsHtml[0];
        vb.popBtnsHtml = btnsHtml[1];
        vb.listHtml = await pageModel.mobHtmlGetList();
        vb.listIds = pageModel.list.ids.join(',');
        vb.count = pageModel.list.count;
        //cmpage.debug(vb.listHtml);
        vb.statusCode = 200;

        return this.json(vb);
    }


    /**
     * 业务模块的编辑页面，调用： /cmpage/mob/edit
     * @method  edit
     * @return {json}  包含HTML片段
     */
    async editAction() {
        let module = cmpage.service('cmpage/module');
        let parms = await module.getModuleByName(this.post('modulename'));
        parms.parmsUrl = JSON.stringify(this.post('parmsUrl'));
        parms.editID = this.post("editID");
        //console.log(page);
        parms.user = await this.session('user');
        let pageModel = cmpage.service(parms.c_path);
        if (think.isEmpty(pageModel)) {
            return this.json({
                statusCode: '300',
                message: parms.modulename + " 的实现类不存在！"
            });
        }
        //cmpage.debug(parms);
        pageModel.mod = parms;
        pageModel.modEdits = await module.getModuleEdit(parms.id);

        let editHtml = await pageModel.mobHtmlGetEdit();
        let editBtnsHtml = await pageModel.mobHtmlGetEditBtns();

        return this.json({
            statusCode: 200,
            editHtml: editHtml,
            editBtnsHtml:editBtnsHtml
        });
    }

    /**
     * 保存业务模块记录信息， POST调用： /cmpage/mob/save
     * @method  save
     * @return {json}
     */
    async saveAction() {
        let parms = this.post();
        let user = await this.session('user');
        cmpage.warn(user);

        parms.c_user = parms.c_user || user.id;
        parms.c_group = (think.isEmpty(parms.c_group) || parms.c_group == 0) ? user.groupID : parms.c_group;
        parms.c_time = parms.c_time || think.datetime();
        parms.c_status = (think.isEmpty(parms.c_status) ? 0 : parms.c_status);
        if (!think.isEmpty(parms.c_country)) { //地区联动，拆分
            let area = parms.c_country.split(',');
            parms.c_province = area[0];
            parms.c_city = area[1];
            parms.c_country = area[2];
        }
        let ret = {
            statusCode: 200,
            message: '保存成功!',
            data: {}
        };

        let module = cmpage.service('cmpage/module');
        let md = await module.getModuleByName(parms.modulename);
        let pageModel = cmpage.service(think.isEmpty(md.c_path) ? 'cmpage/page' : md.c_path);
        pageModel.mod = md;
        pageModel.mod.user = user;
        pageModel.mod.editID = parms["id"] || parms["c_id"] || 0;
        pageModel.modEdits = await module.getModuleEdit(md.id);
        let saveRet = await pageModel.pageSave(parms);
        if(saveRet.statusCode === 200){
            ret.data = pageModel.rec;
            return this.json(ret);
        }else{
            return this.json({
                statusCode: 300,
                message:saveRet.message,
                data:{}
            })
        }
    }

    /**
     * 业务模块的查看页面，一般调用： /cmpage/mob/view
     * @method  view
     * @return {promise}  HTML片段
     */
    async viewAction() {
        let module = cmpage.service('cmpage/module');
        let md = await module.getModuleByName(this.post('modulename'));
        let pageModel = cmpage.service(think.isEmpty(md.c_path) ? 'cmpage/page' : md.c_path);
        pageModel.mod = md;
        pageModel.mod.editID = parseInt(this.post('curID'));
        pageModel.mod.user = await this.session('user');
        pageModel.modEdits = await module.getModuleEdit(md.id);
        pageModel.modCols = await module.getModuleCol(md.id);

        let viewHtml = await pageModel.mobHtmlGetView()
        return this.json({
            statusCode: 200,
            viewHtml: viewHtml
        });
    }


    /**
     * APP上传文件的URL接口，调用： /cmpage/mob/file_add </br>
     * 通用的附件上传，保持与表 t_file </br>
     * 如果仅仅是单个文件上传，然后取得保存后的文件路径名，则调用 /cmpage/page/upload_file
     * @method  updateFile
     * @return {json}  状态
     */
    async file_addAction(){
        const fs = require('fs');
        const path = require('path');
        const rename = think.promisify(fs.rename, fs); // 通过 promisify 方法把 rename 方法包装成 Promise 接口

        let parms = this.post();
        debug(parms, 'cmpage.mob.C.file_add - parms');

        const file = this.ctx.file('fileFile');
        if (think.isEmpty(file)) {
            return this.json({
                statusCode: 300,
                message: '您上传了无效的文件！',
                filename: ''
            });
        }
        let fileName = `/static/upfiles/${parms.c_link_type}/${cmpage.datetime().substring(0,4)}/${file.name}`;
        let saveFile = path.join(think.ROOT_PATH, `www${fileName}`);
        debug(saveFile, 'cmpage.mob.C.file_add - saveFile');

        think.mkdir(path.dirname(saveFile));
        var readStream = fs.createReadStream(file.path)
        var writeStream = fs.createWriteStream(saveFile);
        readStream.pipe(writeStream);
        readStream.on('end', function () {
            fs.unlinkSync(file.path);
        });

        let user = await this.session('user');
        let fileRec = this.cmpage.objPropertysFromOtherObj({},parms,'c_link,c_link_type,c_name,c_memo');
        fileRec.c_type = 1;
        fileRec.c_status = 0;
        fileRec.c_path = fileName;
        fileRec.c_user = user.id;
        fileRec.c_time = new Date();
        await cmpage.service('cmpage/base').model('t_file').add(fileRec);

        return this.json({
            statusCode: 200,
            message: '',
            filename: fileName
        });        
    }
    

}